package com.zcp.pcsuitall;

import java.io.IOException;
import java.io.StringWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;

import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.util.Xml;

/**
 * 发送短信后广播接收
 *
 */
public class SendReceive extends BroadcastReceiver {
	private static String SMS_SEND_ACTIOIN = "SMS_SEND_ACTIOIN";
	private static String SMS_DELIVERED_ACTION = "SMS_DELIVERED_ACTION";
	private static String TAG = "SendDataReceive";
	private int mResultCode;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
		System.out.println("mResultCode-----------==="+mResultCode);
		
		Log.i(TAG, "SendReceive begin.");
		if (intent.getAction().equals(SMS_SEND_ACTIOIN)) {
			try {
				Log.i(TAG, "sms send getResultCode is "+ getResultCode());
				sendBroadcast(context, intent);
			} catch (Exception e) {
				e.getStackTrace();
			}
		} else if (intent.getAction().equals(SMS_DELIVERED_ACTION)) {
			try {
				Log.i(TAG, "sms send deliver getResultCode is "+ getResultCode());
				sendBroadcast(context, intent);
			} catch (Exception e) {
				e.getStackTrace();
			}
		}
	}

	private void sendBroadcast(Context context, Intent intent) {
		Date dateTime = new Date(0l);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Bundle bundle=intent.getBundleExtra("bundle");
		String body = bundle.getString("body");
		String address = bundle.getString("address");
		String date = bundle.getString("date");
		String send_id = bundle.getString("send_id");
		int type = 2;
		Log.i(TAG,"--address="+address+"--body="+body+"--date="+date);
		
		mResultCode = getResultCode();
		System.out.println("mResultCode=="+mResultCode);
		
		//发送短信前先把内容存到发件箱中
		ContentValues values = new ContentValues();
		values.put("address", address);
		values.put("date", bundle.getString("date"));
		values.put("status", "-1");
		values.put("read", 1);
		values.put("body", body);
		
		Uri sendUri = null;
		if(mResultCode == Activity.RESULT_OK){
			values.put("type", 2);//发送成功
			sendUri = context.getContentResolver().insert(Uri.parse("content://sms"), values);
		}else if((mResultCode == SmsManager.RESULT_ERROR_RADIO_OFF) ||
                (mResultCode == SmsManager.RESULT_ERROR_NO_SERVICE)){
			type  = 6;
		    values.put("type", 6);//其它问题，显示正在发送
		    sendUri = context.getContentResolver().insert(Uri.parse("content://sms"), values);
		}else{
			type  = 5;
			values.put("type", 5);//发送失败
			sendUri = context.getContentResolver().insert(Uri.parse("content://sms"), values);
		}
		int id = (int)ContentUris.parseId(sendUri);
		System.out.println("/////send parseId="+id);
			
		dateTime.setTime(Long.parseLong(date));
		String outDate = dateFormat.format(dateTime);
		StringWriter writer = new StringWriter();
        XmlSerializer serializer = Xml.newSerializer();
		if (bundle != null) {
			try {
				Action action = new Action("HaveMessage", null);
		        serializer.setOutput(writer);
	            XmlDataDealWith.createPre(action, serializer);
	            serializer.startTag(null, "item");
	            writeSingleTextToXml(serializer, "id", id+"");
	            writeSingleTextToXml(serializer, "thread_id", null);
	            writeSingleTextToXml(serializer, "address", address);
	            writeSingleTextToXml(serializer, "person_id", null);
	            writeSingleTextToXml(serializer, "date", outDate);
	            writeSingleTextToXml(serializer, "protocol", null);
	            writeSingleTextToXml(serializer, "is_read", null);
	            writeSingleTextToXml(serializer, "status", null);
	            writeSingleTextToXml(serializer, "type", type+"");
	            writeSingleTextToXml(serializer, "reply_path_present", null);
	            writeSingleTextToXml(serializer, "subject", null);
	            writeSingleTextToXml(serializer, "body", body);
	            writeSingleTextToXml(serializer, "service_center", null);
	            writeSingleTextToXml(serializer, "locked", null);
	            writeSingleTextToXml(serializer, "send_id", send_id);
	            serializer.endTag(null, "item");
	            serializer.text("");
	            serializer.endTag("", "data");
	            serializer.endTag("", "root");
	            serializer.endDocument();
	            System.out.println("send xml value:"+writer.toString());
				Intent dataIntent = new Intent(SocketService.SEND_MESSAGE_REPORT_ACTIOIN);
				dataIntent.putExtra(SocketService.SEND_DATA_KEY,writer.toString());
				context.sendBroadcast(dataIntent);// 向SocketService上报短信
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
     * 创建一个包含单个值的XML节点，如<TAG>value</TAG>,写入serializer中
     */
    private void writeSingleTextToXml(XmlSerializer serializer, String tag, String value)
            throws IllegalArgumentException, IllegalStateException, IOException {
        // 值为空时不写入XML
        if (value == null)
            value = "";
        serializer.startTag(null, tag);
        serializer.text(value);
        serializer.endTag(null, tag);
    }
}
